package com.stu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stu.commons.ServerResponse;
import com.stu.mapper.MycouponMapper;
import com.stu.pojo.*;
import com.stu.service.*;
import com.stu.utils.JwtUtil;  // 替换 TokenUtil 为 JwtUtil
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 订单相关的控制层
 */
@RestController
public class MyorderController {

    @Autowired
    private ICouponService couponService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IMyorderDetailService myorderDetailService;

    @Autowired
    private IMyorderService myorderService;

    @Autowired
    private IMycouponService iMycouponService;

    @Autowired
    private MycouponMapper mycouponMapper;

    @Autowired
    private IAddressService addressService;

    /**
     * 创建订单
     */
    @PostMapping("createMyorder")
    public ModelAndView createMyorder(String addressChosed,Integer couponChosed,Integer couponId,HttpSession session){
        SpikeProduct spikeProduct = (SpikeProduct) session.getAttribute("product");
        Users user = (Users) session.getAttribute("user");
        Integer price = 0;
        if(couponChosed != null)
            price = couponChosed;

        Coupon coupon = couponService.getById(couponId);
        List<Address> addressList = (List<Address>) session.getAttribute("addressList");
        Integer addressId = null;
        for (int i = 0; i < addressList.size(); i++) {
            if (addressChosed.contains(addressList.get(i).getAddressDetail()))
                addressId = addressList.get(i).getAddressId();
        }

        // 创建订单
        Myorder myorder = new Myorder();
        myorder.setAddressId(addressId);
        myorder.setCouponId(couponId);
        myorder.setUserId(user.getUserId());
        myorder.setMyorderNumber(UUID.randomUUID().toString().replace("-", ""));
        myorder.setCouponPrice(Float.valueOf(coupon.getCouponPrice()));
        myorder.setMyorderPrice(spikeProduct.getSpikeProductPrice() - price);

        // 设置订单创建时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String createTime = sdf.format(date);
        myorder.setMyorderCreateTime(createTime);
        myorder.setMyorderStatus(0);

        // 保存订单
        myorderService.saveMyOrder(myorder);

        // 创建订单详情
        MyorderDetail myorderDetail = new MyorderDetail();
        myorderDetail.setMyorderId(myorder.getMyorderId());
        myorderDetail.setMyorderDetailProductNums(1);
        myorderDetail.setProductId(spikeProduct.getProductId());
        myorderDetail.setMyorderDetailStatus(1);
        myorderDetail.setm1("0");
        myorderDetail.setm2("0");

        // 保存订单详情
        myorderDetailService.saveMyorderDetail(myorderDetail);

        // 页面分发
        ModelAndView mav = new ModelAndView();
        mav.addObject("addressDetail", addressChosed);
        mav.addObject("order", myorder);
        mav.setViewName("pay_order/goPay.jsp");

        // 延时队列：过期将订单状态改为已取消
        rabbitTemplate.convertAndSend("delayExchange", "orderDelayCancel", myorder, message -> {
            // 延时 15 分钟
            message.getMessageProperties().setHeader("x-delay", 1000 * 60 * 15);
            return message;
        });

// 延时队列：订单即将过期提醒
        rabbitTemplate.convertAndSend("delayExchange", "orderDelayTip", myorder, message -> {
            // 延时 10 分钟
            message.getMessageProperties().setHeader("x-delay", 1000 * 60 * 10);
            return message;
        });

        return mav;
    }

    /**
     * 消费者处理订单支付完成后修改订单状态
     */
    @RabbitHandler
    @RabbitListener(queues = "payOrderQueue")
    public void changeOrderStatus(Myorder myorder, Message message, Channel channel) {
        try {
            if (myorder.getMyorderStatus() == 0)
                myorder.setMyorderStatus(1);
            myorderService.updateMyorder(myorder);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 消费者处理订单支付后更新优惠券状态
     */
    @RabbitHandler
    @RabbitListener(queues = "newUpdateCouponQueue")
    public void changeMyCouponStatus(Myorder myorder, Message message, Channel channel) {
        Integer couponId = myorder.getCouponId();
        Integer userId = myorder.getUserId();

        // 查询用户的优惠券
        QueryWrapper<Mycoupon> wrapper = new QueryWrapper<>();
        wrapper.eq("coupon_id", couponId);
        wrapper.eq("user_id", userId);
        Mycoupon mycoupon = mycouponMapper.selectOne(wrapper);

        // 更新优惠券状态
        Integer update = iMycouponService.update(mycoupon);
        if (update > 0) {
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取所有订单
     */
    @GetMapping("getAllOrders")
    public ModelAndView getAllOrders(String token) {
        // 使用 JwtUtil 替换 TokenUtil
        Integer userId = Integer.parseInt(JwtUtil.getUserIdFromToken(token)); // 使用 JwtUtil 提取用户 ID
        ServerResponse result = myorderService.getAll(userId);

        ModelAndView mav = new ModelAndView();
        if (result.getResultcode() == 200) {
            mav.addObject("result", result.getData());
            mav.setViewName("/personal/myOrder.jsp");
        }
        return mav;
    }

    /**
     * 更新订单状态
     */
    @PostMapping("updateStatus")
    public int updateStatus(String orderNum) {
        return myorderService.updateOrderStatus(orderNum);
    }

    /**
     * 跳转到支付页面
     */
    @GetMapping("zhifu/{orderNum}/{orderPrice}/{addressId}")
    public ModelAndView zhifu(@PathVariable("orderNum") String orderNum, @PathVariable("orderPrice") Float orderPrice, @PathVariable("addressId") Integer addressId) {
        Address address = addressService.getById(addressId);
        String detail = address.getAddressProvince() + address.getAddressCity() + address.getAddressArea() + address.getAddressDetail();

        Myorder myorder = new Myorder();
        myorder.setMyorderNumber(orderNum);
        myorder.setMyorderPrice(orderPrice);

        ModelAndView mav = new ModelAndView();
        mav.addObject("order", myorder);
        mav.addObject("addressDetail", detail);
        mav.setViewName("/pay_order/goPay.jsp");
        return mav;
    }

    /**
     * 跳转到发布页面
     */
    @GetMapping("tofabiao/{orderId}")
    public ModelAndView tofabiao(@PathVariable("orderId") Integer orderId) {
        Myorder myorder = myorderService.selectById(orderId);
        List<MyorderDetail> myorderDetail = myorderDetailService.getByMyorderId(orderId);

        ModelAndView mav = new ModelAndView();
        mav.addObject("result", myorder);
        mav.addObject("proid", myorderDetail.get(0).getProductId());
        mav.setViewName("/personal/fabiao.jsp");
        return mav;
    }
}
